import pickle

student_infos = []


def add_info():
    new_infos = {}
    new_infos['name'] = input("请输入学生姓名：")
    new_infos['sex'] = input("请输入学生性别：")
    student_infos.append(new_infos)


def del_info():
    del_number = int(input("请输入要删除的学生序号："))
    if 0 <= del_number < len(student_infos):
        del student_infos[del_number]
        print("删除成功！")
    else:
        print("输入序号有误！")


def modify_info():
    modify_number = int(input("请输入要修改的学生序号："))
    if 0 <= modify_number < len(student_infos):
        student_infos[modify_number]['name'] = input("请输入修改后的姓名：")
        student_infos[modify_number]['sex'] = input("请输入修改后的性别：")
        print("修改成功！")
    else:
        print("输入序号有误！")


def save_to_file():
    with open('backup.data', 'wb') as file:
        pickle.dump(student_infos, file)
    print("数据已保存到文件中！")


def recover_data():
    global student_infos
    try:
        with open('backup.data', 'rb') as file:
            student_infos = pickle.load(file)
        print("数据已恢复！")
    except FileNotFoundError:
        print("未找到备份文件，无法恢复数据！")


def main():
    recover_data()

    while True:
        print("\n学生信息管理系统")
        print("1. 添加学生信息")
        print("2. 删除学生信息")
        print("3. 修改学生信息")
        print("4. 保存数据到文件")
        print("0. 退出程序")
        key = input("请输入对应的操作编号：")

        if key == '1':
            add_info()
        elif key == '2':
            del_info()
        elif key == '3':
            modify_info()
        elif key == '4':
            save_to_file()
        elif key == '0':
            quit_confirm = input("是否确认退出程序？(y/n): ")
            if quit_confirm.lower() == 'y':
                break
        else:
            print("输入有误，请重新输入！")


if __name__ == "__main__":
    main()
